import os
import asyncio
from typing import Optional, Dict, Any
from concurrent.futures import ThreadPoolExecutor
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(name)s: %(message)s'
)
logger = logging.getLogger(__name__)

try:
    from funasr import AutoModel
except ImportError:
    logger.warning("警告: FunASR 未安装，请运行: pip install funasr")
    AutoModel = None


class SimpleASRService:
    """简化版ASR服务类"""
    
    def __init__(self):
        self.model = None  # 统一的AutoModel实例
        
        # 并发支持 线程池+异步模式
        self.executor = ThreadPoolExecutor(max_workers=2)  # 限制并发数
        self.semaphore = asyncio.Semaphore(2)  # 异步信号量
        
    def initialize(self) -> bool:
        """初始化ASR模型"""
        try:
            if AutoModel is None:
                logger.error("AutoModel未加载，无法初始化ASR服务")
                return False
                
            # 设置模型缓存目录
            model_cache_dir = os.path.join("models")
            os.makedirs(model_cache_dir, exist_ok=True)
            
            logger.info("正在加载ASR模型（包含语音识别、VAD、标点恢复、说话人识别）...")
            # 使用AutoModel一次性加载所有四个模型
            self.model = AutoModel(
                model="paraformer-zh", 
                model_revision="v2.0.4",
                vad_model="fsmn-vad", 
                vad_model_revision="v2.0.4",
                punc_model="ct-punc-c", 
                punc_model_revision="v2.0.4",
                spk_model="cam++", 
                spk_model_revision="v2.0.2",
                disable_update=True,
                cache_dir=model_cache_dir
            )
            
            logger.info("ASR模型加载完成！")
            return True
            
        except Exception as e:
            logger.error(f"模型加载失败: {str(e)}")
            return False
    
    def _transcribe_sync(self, audio_path: str) -> Dict[str, Any]:
        """同步转录方法（在线程池中执行）"""
        try:
            if self.model is None:
                raise RuntimeError("模型未初始化")
                
            # 使用统一的model进行转录，包含所有功能
            result = self.model.generate(input=audio_path)
            
            # 处理转录结果
            if result and len(result) > 0:
                # 获取转录文本
                text = result[0].get('text', '')
                
                return {
                    'success': True,
                    'text': text,
                    'raw_text': text,
                    'segments': result,
                    'audio_path': audio_path
                }
            else:
                return {
                    'success': False,
                    'error': '转录结果为空',
                    'audio_path': audio_path
                }
                
        except Exception as e:
            logger.error(f"转录同步处理失败: {str(e)}")
            return {
                'success': False,
                'error': str(e),
                'audio_path': audio_path
            }
    
    async def transcribe(self, audio_path: str) -> Dict[str, Any]:
        """异步转录方法"""
        async with self.semaphore:
            # 检查文件是否存在
            if not os.path.exists(audio_path):
                logger.warning(f"文件不存在: {audio_path}")
                return {
                    'success': False,
                    'error': f'文件不存在: {audio_path}'
                }
            
            # 在线程池中执行同步转录
            loop = asyncio.get_event_loop()
            result = await loop.run_in_executor(
                self.executor, 
                self._transcribe_sync, 
                audio_path
            )
            
            return result
    
    def cleanup(self):
        """清理资源"""
        logger.info("正在清理ASR服务资源...")
        if self.executor:
            self.executor.shutdown(wait=True)
        logger.info("ASR服务资源清理完成")


# 全局ASR服务实例
_asr_service: Optional[SimpleASRService] = None


def get_asr_service() -> SimpleASRService:
    """获取ASR服务实例（单例模式）"""
    global _asr_service
    if _asr_service is None:
        _asr_service = SimpleASRService()
    return _asr_service